

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="前言fixture是pytest的一个闪光点，pytest要精通怎么能不学习fixture呢？ fixture是pytest特有的功能，它用pytest.fixture标识，定义在函数前面。 在你编写测试函数的时候，你可以将此函数名称做为传入参数，pytest将会以依赖注入方式，将该函数的返回值作为测试函数的传入参数。 fixture有明确的名字，在其他函数，模块，类或整个工程调用它时会被激活。">
<meta property="og:type" content="article">
<meta property="og:title" content="pytest必学之fixture">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2023/05/12/autoTest/pytest%E5%BF%85%E5%AD%A6%E4%B9%8Bfixture/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="前言fixture是pytest的一个闪光点，pytest要精通怎么能不学习fixture呢？ fixture是pytest特有的功能，它用pytest.fixture标识，定义在函数前面。 在你编写测试函数的时候，你可以将此函数名称做为传入参数，pytest将会以依赖注入方式，将该函数的返回值作为测试函数的传入参数。 fixture有明确的名字，在其他函数，模块，类或整个工程调用它时会被激活。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-05-12T02:47:05.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.245Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="自动化测试">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="自动化测试框架">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>pytest必学之fixture - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="pytest必学之fixture"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-05-12 10:47" pubdate>
          2023年5月12日 上午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          11k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">pytest必学之fixture</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>fixture是pytest的一个闪光点，pytest要精通怎么能不学习fixture呢？</p>
<p>fixture是pytest特有的功能，它用pytest.fixture标识，定义在函数前面。</p>
<p>在你编写测试函数的时候，你可以将此函数名称做为传入参数，pytest将会以依赖注入方式，将该函数的返回值作为测试函数的传入参数。</p>
<p>fixture有明确的名字，在其他函数，模块，类或整个工程调用它时会被激活。</p>
<p>比如我们之前介绍过的 <strong>setup/teardown</strong> 就可以通过fixture来完成</p>
<p>但fixture却可以不像 <strong>setup/teardown</strong> 每次都运行, 他是可控的.</p>
<h1 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-comment"># 通过fixture装饰一个函数, 将这个函数声明成fixture</span><br><span class="hljs-comment"># 被用例函数调用时, 会在函数执行之前调用</span><br><span class="hljs-meta">@pytest.fixture()</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">before</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;------&gt;before&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self, before</span>):  <span class="hljs-comment"># 通过显式声明参数, 就可以调用同名的fixture函数</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>):  <span class="hljs-comment"># 没声明则不调用</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;-v&#x27;</span>, __file__])  <br><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">collected 2 items                                                 </span><br><span class="hljs-string"></span><br><span class="hljs-string">test3.py::TestCase::test_a ------&gt;before</span><br><span class="hljs-string">-------&gt;test_a</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase::test_b -------&gt;test_b</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-comment"># 通过fixture装饰一个函数, 将这个函数声明成fixture</span><br><span class="hljs-comment"># 被用例函数调用时, 会在函数执行之前调用</span><br><span class="hljs-meta">@pytest.fixture()</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">before</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;------&gt;before&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():<br><br><span class="hljs-meta">    @pytest.mark.usefixtures(<span class="hljs-params"><span class="hljs-string">&#x27;before&#x27;</span></span>)  </span><span class="hljs-comment"># 通过显式声明参数, 就可以调用同名的fixture函数</span><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):  <span class="hljs-comment"># 没声明则不调用</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;-v&#x27;</span>, __file__])  <br><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">collected 2 items                                                                                                                                                                                                                  </span><br><span class="hljs-string"></span><br><span class="hljs-string">test3.py::TestCase::test_a ------&gt;before</span><br><span class="hljs-string">-------&gt;test_a</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase::test_b -------&gt;test_b</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string"></span><br><span class="hljs-string">通过pytest.mark.usefixtures直接调用</span><br><span class="hljs-string">但该方式, 用例函数就是用不到fixture返回的值</span><br><span class="hljs-string">所以不需要参数值, 只需要一个前置动作的, 可以使用该方式</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-comment"># 通过fixture装饰一个函数, 将这个函数声明成fixture</span><br><span class="hljs-comment"># 被用例函数调用时, 会在函数执行之前调用</span><br><span class="hljs-meta">@pytest.fixture()</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">before</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;------&gt;before&quot;</span>)<br><br><span class="hljs-meta">@pytest.mark.usefixtures(<span class="hljs-params"><span class="hljs-string">&#x27;before&#x27;</span></span>)  </span><span class="hljs-comment"># 通过显式声明参数, 就可以调用同名的fixture函数</span><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;-v&#x27;</span>, __file__])  <br><br><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">装饰一个类的时候, 类下的每个用例函数运行前, 都会调用fixture函数</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>


<h2 id="autouse"><a href="#autouse" class="headerlink" title="autouse"></a>autouse</h2><p>fixture还有一个参数, 叫做 <code>autouse</code></p>
<p>顾名思义, 就是<strong>自动使用</strong>的意思.</p>
<p>比如说, 你认为每一条用例都会做的一个前置动作, 那么你就可以<code>autouse</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-comment"># 通过fixture装饰一个函数, 将这个函数声明成fixture</span><br><span class="hljs-comment"># 被用例函数调用时, 会在函数执行之前调用</span><br><span class="hljs-meta">@pytest.fixture(<span class="hljs-params">autouse=<span class="hljs-literal">True</span></span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">before</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;------&gt;before&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;-v&#x27;</span>, __file__])  <br><br><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">collected 2 items                                                                                                                                                                                                                  </span><br><span class="hljs-string"></span><br><span class="hljs-string">test3.py::TestCase::test_a ------&gt;before</span><br><span class="hljs-string">-------&gt;test_a</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase::test_b ------&gt;before</span><br><span class="hljs-string">-------&gt;test_b</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<p>可以发现, 我们使用了 <code>autouse</code> 后, 原本在用例函数上使用的 <code>usefixture</code> 被我们去掉了</p>
<p>运行后, 每条用例都调用了 <code>before</code></p>
<h2 id="scope"><a href="#scope" class="headerlink" title="scope"></a>scope</h2><p>在学习完 <code>函数/闭包/装饰器</code> 后, 大家肯定对scope不会陌生</p>
<p>也就是<strong>作用域</strong>的意思.</p>
<p>接上面的内容, 我们可以通过 <code>autouse</code> 来自动运行, 但是这个时候, 它是每一条用例函数都会运行.</p>
<p>但很多时候, 我们只是希望他运行在某些函数下, 这个时候, 就得需要 <code>scope</code> 加以控制.</p>
<p>fixture scope分为四个类型:</p>
<ul>
<li>function：每个test都运行，默认是function的scope</li>
<li>class：每个class只运行一次</li>
<li>module：每个module只运行一次</li>
<li>session：每个session只运行一次</li>
</ul>
<h3 id="function"><a href="#function" class="headerlink" title="function"></a>function</h3><p>这是scope的默认状态, 不指定时就是function, 所以不做过多介绍.</p>
<h3 id="class"><a href="#class" class="headerlink" title="class"></a>class</h3><p>顾名思义, 作用域在 <strong>测试类</strong> 上</p>
<p>每个class中, 不管有多少个用例函数, 都会只执行一次</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-meta">@pytest.fixture(<span class="hljs-params">scope=<span class="hljs-string">&quot;class&quot;</span>, autouse=<span class="hljs-literal">True</span></span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">before</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;------&gt;before&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase2</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;-v&#x27;</span>, __file__])  <br><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">collected 4 items                                                                                                                                                                                                                  </span><br><span class="hljs-string"></span><br><span class="hljs-string">test3.py::TestCase::test_a ------&gt;before</span><br><span class="hljs-string">-------&gt;test_a</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase::test_b -------&gt;test_b</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase2::test_a ------&gt;before</span><br><span class="hljs-string">-------&gt;test_a</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase2::test_b -------&gt;test_b</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<p>可以发现, 在不同的 测试类 中, fixture before 只执行了一次</p>
<p>如果把一个测试类当成一整条测试用例, 类中的方法最测试步骤</p>
<p>那么通过声明scope为class, 则可以将其作为一种前置动作.</p>
<h3 id="module"><a href="#module" class="headerlink" title="module"></a>module</h3><p><code>module</code> 在这里, 你可以理解成一个脚本文件</p>
<p>也就是说, 一个脚本文件内, 不管有多少 用例函数 都只执行一次 fixture</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-meta">@pytest.fixture(<span class="hljs-params">scope=<span class="hljs-string">&quot;module&quot;</span>, autouse=<span class="hljs-literal">True</span></span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">before</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;------&gt;before&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase2</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;-v&#x27;</span>, __file__])  <br><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">collected 4 items</span><br><span class="hljs-string"></span><br><span class="hljs-string">test3.py::TestCase::test_a ------&gt;before</span><br><span class="hljs-string">-------&gt;test_a</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase::test_b -------&gt;test_b</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase2::test_a -------&gt;test_a</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase2::test_b -------&gt;test_b</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<h3 id="session"><a href="#session" class="headerlink" title="session"></a>session</h3><p><code>session</code> 就是当前运行的意思</p>
<p>简单来说, 就是每次执行的时候就只运行一次</p>
<p>不管你有多少个 <strong>用例文件</strong>, 只会运行一次</p>
<p>这里就简单举个例子, 这个具体的现象, 要后续学习完 <strong>conftest</strong> 后, 才能很好的展示</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-meta">@pytest.fixture(<span class="hljs-params">scope=<span class="hljs-string">&quot;session&quot;</span>, autouse=<span class="hljs-literal">True</span></span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">before</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;------&gt;before&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase2</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;-v&#x27;</span>, __file__])  <br></code></pre></td></tr></table></figure>

<h2 id="fixture-返回值"><a href="#fixture-返回值" class="headerlink" title="fixture 返回值"></a>fixture 返回值</h2><p>fixture函数是支持写返回值, 来给用例函数使用的</p>
<p>可以想象一个需求, 我使用fixture, 为所有测试用例函数进行前置初始化</p>
<p>在其中, 我们 <strong>连接数据库</strong>, 并且将连接实例返回出来, 共给用例函数使用</p>
<p>这样一来, 我每条用例都不需要再去初始化连接数据库了.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-meta">@pytest.fixture(<span class="hljs-params">scope=<span class="hljs-string">&quot;module&quot;</span>, autouse=<span class="hljs-literal">True</span></span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">before</span>():<br>    connectObj = <span class="hljs-string">&quot;连接连接&quot;</span>  <span class="hljs-comment"># 假设这是连接数据库后的实例对象</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;---------&gt; 数据库已连接&quot;</span>)<br>    <span class="hljs-keyword">return</span> connectObj<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self, before</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;我要用你了哦 <span class="hljs-subst">&#123;before&#125;</span>&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self, before</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;我要用你了哦 <span class="hljs-subst">&#123;before&#125;</span>&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase2</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;-v&#x27;</span>, __file__])<br><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">collected 4 items                                                                                                                                                                                                                  </span><br><span class="hljs-string"></span><br><span class="hljs-string">test3.py::TestCase::test_a ---------&gt; 数据库已连接</span><br><span class="hljs-string">-------&gt;test_a</span><br><span class="hljs-string">-------&gt;我要用你了哦 连接连接</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase::test_b -------&gt;test_b</span><br><span class="hljs-string">-------&gt;我要用你了哦 连接连接</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase2::test_a -------&gt;test_a</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase2::test_b -------&gt;test_b</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<p>配合代码以及运行结果, 我们可以很清晰的看到这个需求我们通过fixture + 返回值 完美的实现了</p>
<h2 id="fixture-后置处理"><a href="#fixture-后置处理" class="headerlink" title="fixture 后置处理"></a>fixture 后置处理</h2><p>之前的介绍, 都是围绕着fixture的 <strong>前置动作</strong></p>
<p>实际上, fixture还支持 <strong>后置处理</strong></p>
<p>同样的, 书接上面</p>
<blockquote>
<p>我们为每个用例函数都预先初始化了数据库连接<br>但我们同时希望, 用例执行结束后, 我们要关闭数据库连接<br>我们总不能在最后一条用例去做这件事情, 因为这是不容易维护的, 也是违背了我们的意愿<br>所以, 我们还是得从fixture下手</p>
</blockquote>
<p>实际上 实现这个需求, 我们只需要把 <code>return</code> 换成 <code>yield</code></p>
<blockquote>
<p>关于yield是什么, 有兴趣的可以去搜索一下 <strong>生成器</strong></p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-meta">@pytest.fixture(<span class="hljs-params">scope=<span class="hljs-string">&quot;module&quot;</span>, autouse=<span class="hljs-literal">True</span></span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">before</span>():<br>    connectObj = <span class="hljs-string">&quot;连接连接&quot;</span>  <span class="hljs-comment"># 假设这是连接数据库后的实例对象</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;---------&gt; 数据库已连接&quot;</span>)<br>    <span class="hljs-keyword">yield</span> connectObj  <span class="hljs-comment"># 将return 换成 yield</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;---------&gt; 数据库已关闭连接&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self, before</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;我要用你了哦 <span class="hljs-subst">&#123;before&#125;</span>&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self, before</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;我要用你了哦 <span class="hljs-subst">&#123;before&#125;</span>&quot;</span>)<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase2</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_b&quot;</span>)<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    pytest.main([<span class="hljs-string">&#x27;-s&#x27;</span>, <span class="hljs-string">&#x27;-v&#x27;</span>, __file__])<br><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">collected 4 items                                                                                                                                                                                                                  </span><br><span class="hljs-string"></span><br><span class="hljs-string">test3.py::TestCase::test_a ---------&gt; 数据库已连接</span><br><span class="hljs-string">-------&gt;test_a</span><br><span class="hljs-string">-------&gt;我要用你了哦 连接连接</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase::test_b -------&gt;test_b</span><br><span class="hljs-string">-------&gt;我要用你了哦 连接连接</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase2::test_a -------&gt;test_a</span><br><span class="hljs-string">PASSED</span><br><span class="hljs-string">test3.py::TestCase2::test_b -------&gt;test_b</span><br><span class="hljs-string">PASSED---------&gt; 数据库已关闭连接</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br></code></pre></td></tr></table></figure>

<p>从结果上我们可以发现, 在用例运行结束的最后, 我们已经关闭了数据库的连接.</p>
<h1 id="conftest"><a href="#conftest" class="headerlink" title="conftest"></a>conftest</h1><p>conftest是目前最好的使用fixture的方案, 具备以下特点:</p>
<ul>
<li>可以跨.py文件调用，有多个.py文件调用时，可让conftest.py只调用了一次fixture，或调用多次fixture</li>
<li>conftest.py与运行的用例要在同一个pakage下，并且有init.py文件, <strong>现在不是强制要求了</strong></li>
<li>不需要import导入 conftest.py，pytest用例会自动识别该文件，放到项目的根目录下就可以全局</li>
<li>目录调用了，如果放到某个package下，那就在该package内有效，可有多个conftest.py</li>
<li>conftest.py配置脚本名称是固定的，不能改名称</li>
<li>conftest.py文件不能被其他文件导入</li>
<li>所有同目录测试文件运行前都会执行conftest.py文件</li>
</ul>
<h2 id="基本使用-1"><a href="#基本使用-1" class="headerlink" title="基本使用"></a>基本使用</h2><p>首先我们可以新建一个 <strong>testcase</strong> 文件夹</p>
<p>在其中新建好 <strong>conftest.py/test_1.py/test_2.py</strong></p>
<p>目录结构像这个样子:</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs sh">├─ testcase<br>│  ├─ conftest.py<br>│  ├─ test_1.py<br>│  ├─ test_2.py<br></code></pre></td></tr></table></figure>

<p>conftest.py:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-meta">@pytest.fixture()</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">before</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;-----------&gt;before&quot;</span>)<br></code></pre></td></tr></table></figure>

<p>test_1.py:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self, before</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_1_test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_1_test_b&quot;</span>)<br></code></pre></td></tr></table></figure>

<p>test_2.py:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self, before</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_2_test_a&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_2_test_b&quot;</span>)<br></code></pre></td></tr></table></figure>

<p>这个时候, 我们就需要在命令行运行: pytest -s -v testcase</p>
<p>直接运行testcase文件夹下的所有用例文件</p>
<p>结果:</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs txt">testcase/test_1.py::TestCase::test_a -----------&gt;before<br>-------&gt;test_1_test_a<br>PASSED<br>testcase/test_1.py::TestCase::test_b -------&gt;test_1_test_b<br>PASSED<br>testcase/test_2.py::TestCase::test_a -----------&gt;before<br>-------&gt;test_2_test_a<br>PASSED<br>testcase/test_2.py::TestCase::test_b -------&gt;test_2_test_b<br>PASSED<br></code></pre></td></tr></table></figure>

<p>这个时候, 你可以发现, fixture能够正常的定义与使用</p>
<p>并且! 它有一个专门维护的地方, 你还可以让fixture同时作用于该文件夹下的所有用例文件.</p>
<h2 id="scope-”session”"><a href="#scope-”session”" class="headerlink" title="scope=”session”"></a>scope=”session”</h2><p>还记得我们之前说过的, scope=”session” 要留到这边来展示吗?</p>
<p>没错, conftest既然支持使用fixture</p>
<p>所以fixture本身所有的 <strong>scope/前置/后置/autouse</strong> 都被保留了</p>
<p>conftest.py:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-meta">@pytest.fixture(<span class="hljs-params">scope=<span class="hljs-string">&quot;session&quot;</span>, autouse=<span class="hljs-literal">True</span></span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">before</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;-----------&gt;before&quot;</span>)<br></code></pre></td></tr></table></figure>

<p>这个时候, 我们就需要在命令行运行: pytest -s -v testcase</p>
<p>结果:</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs txt">testcase/test_1.py::TestCase::test_a -----------&gt;before<br>-------&gt;test_1_test_a<br>PASSED<br>testcase/test_1.py::TestCase::test_b -------&gt;test_1_test_b<br>PASSED<br>testcase/test_2.py::TestCase::test_a -------&gt;test_2_test_a<br>PASSED<br>testcase/test_2.py::TestCase::test_b -------&gt;test_2_test_b<br>PASSED<br></code></pre></td></tr></table></figure>

<p>这个时候, 你可以发现, 即使有<strong>两个及以上</strong>的用例文件</p>
<p>fixture设置了 <strong>scope=”session”</strong> 后, 只会在当前运行时执行一次.</p>
<h2 id="自定义参数"><a href="#自定义参数" class="headerlink" title="自定义参数"></a>自定义参数</h2><p>这个需求, 实际上是很常见的.</p>
<p>比如, 我们在 <strong>持续集成</strong> 的构建中, 我们的自动化测试也许是通过jenkins下发命令来执行的</p>
<p>我们可以在下发命令时, 定义一下自定义参数, 来达到一些定制化运行的方式.</p>
<p>可以举个例子:</p>
<blockquote>
<p>我的用例执行是维护在 <strong>测试平台</strong> 上面的<br>平台对每一条用例, 都会有一个 <strong>caseId</strong><br>我通过jenkins下发命名时, 传入这个caseId<br>用例执行结束后, 通过caseId, 调用平台接口, 将结果回显到 <strong>测试平台</strong> 中</p>
</blockquote>
<p>conftest.py:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">pytest_addoption</span>(<span class="hljs-params">parser</span>):<br>    <span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">    定义自定义参数, 函数名写死, 接收参数parser</span><br><span class="hljs-string">    &quot;&quot;&quot;</span><br>    parser.addoption(<br>        <span class="hljs-string">&quot;--caseId&quot;</span>, action=<span class="hljs-string">&quot;store&quot;</span>, <span class="hljs-built_in">help</span>=<span class="hljs-string">&quot;test：表示测试环境，默认test环境&quot;</span><br>    )<br><br><br><span class="hljs-meta">@pytest.fixture(<span class="hljs-params">scope=<span class="hljs-string">&#x27;function&#x27;</span>, autouse=<span class="hljs-literal">True</span></span>)  </span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">getCaseId</span>(<span class="hljs-params">request</span>):<br>    <span class="hljs-keyword">return</span> request.config.getoption(<span class="hljs-string">&#x27;--caseId&#x27;</span>)  <span class="hljs-comment"># 获取传入的caseId 为每一个用例传入caseId</span><br></code></pre></td></tr></table></figure>

<p>test_1.py:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> pytest<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TestCase</span>():<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_a</span>(<span class="hljs-params">self, getCaseId</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_1_test_a&quot;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;caseId: <span class="hljs-subst">&#123;getCaseId&#125;</span>&quot;</span>)  <span class="hljs-comment"># 拿到caseId, 我们就可以正常回传结果了</span><br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">test_b</span>(<span class="hljs-params">self</span>):<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;-------&gt;test_1_test_b&quot;</span>)<br></code></pre></td></tr></table></figure>

<p>这个时候, 我们就需要在命令行运行: pytest -s -v –caseId 10 testcase/test_1.py</p>
<p>结果:</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs txt">collected 2 items<br><br>testcase/test_1.py::TestCase::test_a -------&gt;test_1_test_a<br>caseId: 10<br>PASSED<br>testcase/test_1.py::TestCase::test_b -------&gt;test_1_test_b<br>PASSED<br></code></pre></td></tr></table></figure>

<p>这个时候你可以发现, 我们通过 <code>--caseId 10</code> 传入的10, 能够正常的获取, 并且通过fixture, 能够传递给用例函数</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95/" class="category-chain-item">自动化测试</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95/pytest/" class="category-chain-item">pytest</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95/">#自动化测试</a>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95%E6%A1%86%E6%9E%B6/">#自动化测试框架</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>pytest必学之fixture</div>
      <div>https://walker_kwu.gitee.io/my-blog/2023/05/12/autoTest/pytest必学之fixture/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年5月12日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2023/05/20/autoTest/pytest%E5%BF%85%E5%AD%A6%E4%B9%8Ballure%E6%8A%A5%E5%91%8A/" title="pytest必学之allure报告">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">pytest必学之allure报告</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2023/05/11/autoTest/pytest%E8%BF%9B%E9%98%B6%E4%BD%BF%E7%94%A8/" title="pytest进阶使用">
                        <span class="hidden-mobile">pytest进阶使用</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
